use actix_cors::Cors;
use actix_files::Files;
use actix_web::{web, App, HttpResponse, HttpServer};
use dotenv::dotenv;
use std::env;

mod config;
mod db;
mod handlers;
mod middleware;
mod models;
mod routes;
mod services;
mod utils;

use crate::routes::init_routes;
use crate::services::price_service::PriceService;
use crate::handlers::health;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();
    env_logger::init();

    let host = env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
    let port: u16 = env::var("SERVER_PORT")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(3000);

    // 性能建议：根据CPU核数设置工作线程；生产中可通过环境变量覆盖
    let workers: usize = env::var("WORKER_THREADS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or_else(|| num_cpus::get());

    let price_service = PriceService::new_with_seed(42);

    log::info!("Starting server at http://{}:{}/", host, port);
    HttpServer::new(move || {
        let cors = Cors::permissive();

        App::new()
            .wrap(cors)
            .app_data(web::Data::new(price_service.clone()))
            .service(health::health)
            .configure(init_routes)
            // 提供静态文件目录占位（可用于托前端构建产物）
            .service(Files::new("/public", "./public").show_files_listing())
    })
    .workers(workers)
    .bind((host.as_str(), port))?
    .run()
    .await
}